/************************************************************
 * Project Name         [Thinking_In_Java]
 * File Name            [Java_Util_Prefs_Preferences.java]
 * Creation Date        [24-Jun-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_api_testing;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.prefs.BackingStoreException;
import java.util.prefs.InvalidPreferencesFormatException;
import java.util.prefs.Preferences;

/**
 * java.util.prefs.Preferences
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Java_Util_Prefs_Preferences {

	private static final String storageLocation = "src_01_language_basic/pkg_resources";
	private static final String preferencesFileName = "prefer.xml";

	/**
	 * 导出Preferences
	 * 
	 * @param node
	 */
	public static void exportInformation(Preferences node) {
		FileOutputStream fos = null;
		try {
			File file = new File(storageLocation, preferencesFileName);
			fos = new FileOutputStream(file);
			node.exportNode(fos);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (BackingStoreException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 导入Preferences
	 * 
	 */
	public static void importInformation() {
		FileInputStream fis = null;
		try {
			File file = new File(storageLocation, preferencesFileName);
			fis = new FileInputStream(file);
			Preferences.importPreferences(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InvalidPreferencesFormatException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 测试方法
	 * 
	 * @param args
	 *            命令行参数
	 */
	public static void main(String[] args) {

		// 返回用户配置信息的根节点
		Preferences node = Preferences.userRoot();
		node.put("Username", "Sean");
		node.put("Password", "123456");
		node.put("Gender", "Male");

		Java_Util_Prefs_Preferences.exportInformation(node);
		Java_Util_Prefs_Preferences.importInformation();
	}

}
